package UI;

import javax.swing.JOptionPane;
import Manejadores.ManejadorAgregarUsuarios;

/**
 *
 * @author Facundo
 */
public class IAgregarUsuarios extends javax.swing.JFrame {

    ManejadorAgregarUsuarios manejador;

    /**
     * Creates new form IAgregarUsuarios
     */
    public IAgregarUsuarios() {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(IAgregarUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(IAgregarUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(IAgregarUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(IAgregarUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLNombreUsuario = new javax.swing.JLabel();
        jTFNombreUsuario = new javax.swing.JTextField();
        jLNombre = new javax.swing.JLabel();
        jLApellido = new javax.swing.JLabel();
        jTFNombre = new javax.swing.JTextField();
        jTFApellido = new javax.swing.JTextField();
        jTFTelefono = new javax.swing.JTextField();
        jLTelefono = new javax.swing.JLabel();
        jLDireccion = new javax.swing.JLabel();
        jTFDireccion = new javax.swing.JTextField();
        jLRol = new javax.swing.JLabel();
        jCBRol = new javax.swing.JComboBox();
        jBRegistrar = new javax.swing.JButton();
        jLPassword = new javax.swing.JLabel();
        jPFPassword = new javax.swing.JPasswordField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Agregar nuevos usuarios");
        setMaximumSize(new java.awt.Dimension(320, 240));
        setMinimumSize(new java.awt.Dimension(320, 240));
        setResizable(false);

        jLNombreUsuario.setText("Nombre de usuario");

        jLNombre.setText("Nombre");

        jLApellido.setText("Apellido");

        jLTelefono.setText("Teléfono");

        jLDireccion.setText("Dirección");

        jLRol.setText("Rol");

        jCBRol.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Administrador", "Usuario" }));

        jBRegistrar.setText("Registrar");
        jBRegistrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBRegistrarActionPerformed(evt);
            }
        });

        jLPassword.setText("Password");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLNombre)
                            .addComponent(jLApellido)
                            .addComponent(jLTelefono)
                            .addComponent(jLDireccion)
                            .addComponent(jLRol)
                            .addComponent(jLNombreUsuario)
                            .addComponent(jLPassword))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTFTelefono, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTFApellido, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jPFPassword, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTFNombreUsuario, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTFNombre, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTFDireccion, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jCBRol, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jBRegistrar)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLNombreUsuario)
                    .addComponent(jTFNombreUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLPassword)
                    .addComponent(jPFPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTFNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLNombre))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTFApellido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLApellido))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTFTelefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLTelefono))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTFDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLDireccion))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jCBRol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLRol))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jBRegistrar)
                .addGap(23, 23, 23))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-336)/2, (screenSize.height-265)/2, 336, 265);
    }// </editor-fold>//GEN-END:initComponents

    private void jBRegistrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBRegistrarActionPerformed
        //Tomo los valores ingresados en los textfields       
        String nombreUsuario = this.jTFNombreUsuario.getText();
        char[] pass = this.jPFPassword.getPassword();
        String password = String.copyValueOf(pass);
        String nombre = this.jTFNombre.getText();
        String apellido = this.jTFApellido.getText();
        String telefono = this.jTFTelefono.getText();
        String direccion = this.jTFDireccion.getText();
        String rol = this.jCBRol.getSelectedItem().toString().toLowerCase();
        //Si los datos estan ingresados correctamente los paso al manejador para que los grabe en la base de datos
        if (validarIngresoDatos(nombreUsuario, password, nombre, apellido, telefono, direccion)) {
            //Creo el objeto manejador
            manejador = new ManejadorAgregarUsuarios();
            //El if está porque se checkea que el nombre de usuario no exista ya en la base de datos   
            if (manejador.grabarUsuario(nombreUsuario, password, nombre, apellido, telefono, direccion, rol)) {
                JOptionPane.showMessageDialog(this, "El usuario ha sido grabado correctamente", "Información", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(this, "El nombre de usuario ya existe en la base de datos", "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_jBRegistrarActionPerformed

    private boolean validarIngresoDatos(String nombreUsuario, String password, String nombre, String apellido, String telefono, String direccion) {
        //Primero valido que se hayan ingresado datos
        if (nombreUsuario == null || password == null || nombre == null || apellido == null || telefono == null || direccion == null) {
            JOptionPane.showMessageDialog(this, "Por favor ingrese todos los datos", "Advertencia", JOptionPane.WARNING_MESSAGE);
            return false;
        }//Después si el password es de 6 caracteres mínimo
        else if (password.length() < 6) {
            JOptionPane.showMessageDialog(this, "El password debe ser de 6 caracteres mínimo", "Advertencia", JOptionPane.WARNING_MESSAGE);
            return false;
        }//Después si el password es de 20 caracteres máximo
        else if (password.length() > 20) {
            JOptionPane.showMessageDialog(this, "El password debe ser de 20 caracteres máximo", "Advertencia", JOptionPane.WARNING_MESSAGE);
            return false;
        } //Después si se escribió un caracter que no sea un dígito en el campo de teléfono
        else if (telefono.matches("[^0-9]")) {
            JOptionPane.showMessageDialog(this, "Por favor ingrese un número de teléfono válido (sólo números)", "Advertencia", JOptionPane.WARNING_MESSAGE);
            return false;
        }//Después si se escribió un caracter especial o dígito en el nombre o apellido
        else if (!nombre.matches("[a-zA-Z]") || !apellido.matches("[a-zA-Z]")) {
            JOptionPane.showMessageDialog(this, "Por favor ingrese solo letras en los campos de nombre y apellido", "Advertencia", JOptionPane.WARNING_MESSAGE);
            return false;
        } else {
            return true;
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBRegistrar;
    private javax.swing.JComboBox jCBRol;
    private javax.swing.JLabel jLApellido;
    private javax.swing.JLabel jLDireccion;
    private javax.swing.JLabel jLNombre;
    private javax.swing.JLabel jLNombreUsuario;
    private javax.swing.JLabel jLPassword;
    private javax.swing.JLabel jLRol;
    private javax.swing.JLabel jLTelefono;
    private javax.swing.JPasswordField jPFPassword;
    private javax.swing.JTextField jTFApellido;
    private javax.swing.JTextField jTFDireccion;
    private javax.swing.JTextField jTFNombre;
    private javax.swing.JTextField jTFNombreUsuario;
    private javax.swing.JTextField jTFTelefono;
    // End of variables declaration//GEN-END:variables
}
